package com.ityuwen.mengyagushi.user.service.impl;

import com.ityuwen.mengyagushi.common.util.AuthContextHolder;
import com.ityuwen.mengyagushi.model.user.UserInfo;
import com.ityuwen.mengyagushi.model.user.UserPaidAlbum;
import com.ityuwen.mengyagushi.model.user.UserPaidTrack;
import com.ityuwen.mengyagushi.user.login.LoginClient;
import com.ityuwen.mengyagushi.user.mapper.UserInfoMapper;
import com.ityuwen.mengyagushi.user.mapper.UserPaidAlbumMapper;
import com.ityuwen.mengyagushi.user.mapper.UserPaidTrackMapper;
import com.ityuwen.mengyagushi.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.time.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private LoginClient loginClient;

	@Autowired
	private UserPaidAlbumMapper paidAlbumMapper;

	@Autowired
	private UserPaidTrackMapper paidTrackMapper;

//	@Transactional(rollbackFor = Exception.class)
	@GlobalTransactional
	@Override
	public Map<String, Object> wxLogin(String code, String type) throws FileNotFoundException {

		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("code", code);
		return this.loginClient.login(type, paramMap);
	}

	@Override
	public Boolean isPaidAlbum(Long albumId) {
		return this.paidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>()
				.eq(UserPaidAlbum::getUserId, AuthContextHolder.getUserId())
				.eq(UserPaidAlbum::getAlbumId, albumId)) != null;
	}

	@Override
	public List<UserPaidTrack> getPaidTracks(Long albumId) {
		return this.paidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>()
				.eq(UserPaidTrack::getUserId, AuthContextHolder.getUserId())
				.eq(UserPaidTrack::getAlbumId, albumId));
	}

	@Override
	public void updateVipStatus() {
		UserInfo userInfo = new UserInfo();
		userInfo.setIsVip(0);
		Date date = Date.from(LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant());
		this.update(userInfo, new LambdaUpdateWrapper<UserInfo>().eq(UserInfo::getIsVip, 1).le(UserInfo::getVipExpireTime, date));
	}

	public static void main(String[] args) {
		System.out.println(LocalDate.now());
		System.out.println(java.time.LocalTime.MAX);
		LocalDateTime time = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
		System.out.println(Date.from(time.atZone(ZoneId.systemDefault()).toInstant()));
	}
}
